import os
from typing import List

from ninja import Router, Query
from ninja.pagination import paginate

from apps.manager.customer_service.schema import CustomerServiceRecordFiltersSchema, \
    CustomerServiceRecordResponseSchema, CustomerServiceFeedbackRecordFiltersSchema, \
    CustomerServiceFeedbackRecordResponseSchema, AddCommonQuestionSchema, CommonQuestionResponseSchema, \
    AddServiceSchema, CustomerManageResponseSchema, \
    KnowledgeBaseResponseSchema, AddKnowledgeBaseSchema, ChangeServiceStatusSchema, KnowledgeBasSerializer
from apps.schemas import R
from models.models import CustomerServiceRecords, CustomerServiceFeedbackRecord, CommonQuestion, KnowledgeBase, \
    CustomerManage
from utils.auth import ManagerAuthBearer
from utils.decorators import handle_exception
from utils.paginations import MyPagination
from water_applets import settings

manager_customer_service_router = Router(tags=['客服管理'], auth=ManagerAuthBearer())


@manager_customer_service_router.get("/customer_service_records", summary="获取客服记录列表",
                                     response=List[CustomerServiceRecordResponseSchema])
@handle_exception("获取客服记录列表失败")
@paginate(MyPagination)
def get_customer_service_records(request, filters: CustomerServiceRecordFiltersSchema = Query(...)):
    records = CustomerServiceRecords.objects.all()
    records = filters.filter(records)
    return records


@manager_customer_service_router.get("/customer_service_feedback_records", summary="获取客服反馈记录列表",
                                     response=List[CustomerServiceFeedbackRecordResponseSchema])
@handle_exception("获取客服反馈记录列表失败")
@paginate(MyPagination)
def get_customer_service_feedback_records(request, filters: CustomerServiceFeedbackRecordFiltersSchema = Query(...)):
    records = CustomerServiceFeedbackRecord.objects.all()
    records = filters.filter(records)
    return records


@manager_customer_service_router.get("/common_questions", summary="获取常用问题列表",
                                     response=List[CommonQuestionResponseSchema])
@handle_exception("获取常用问题列表失败")
@paginate(MyPagination)
def get_common_questions(request):
    records = CommonQuestion.objects.all()
    return records


@manager_customer_service_router.post("/common_question", summary="添加常用问题")
@handle_exception("添加常用问题失败")
def get_common_question(request, data: AddCommonQuestionSchema):
    CommonQuestion.objects.create(**data.dict())
    return R.ok(msg="添加成功")


@manager_customer_service_router.delete("/common_question/{question_id}", summary="删除常用问题")
@handle_exception("删除常用问题失败")
def delete_common_question(request, question_id: int):
    if not CommonQuestion.objects.filter(id=question_id).exists():
        return R.error("该常用问题不存在")
    record = CommonQuestion.objects.filter(id=question_id).first()
    record.delete()
    return R.ok(msg="删除成功")


@manager_customer_service_router.put("/common_question/{question_id}", summary="修改常用问题")
@handle_exception("修改常用问题失败")
def update_common_question(request, question_id: int, data: AddCommonQuestionSchema):
    if not CommonQuestion.objects.filter(id=question_id).exists():
        return R.error("该常用问题不存在")
    if data.question == "" or data.answer == "":
        return R.error("问题或回答不能为空")
    record = CommonQuestion.objects.filter(id=question_id).first()
    if not record:
        return R.error("该问题不存在")
    record.question = data.question
    record.answer = data.answer
    record.save()
    return R.ok(msg="修改成功")


@manager_customer_service_router.get("/knowledge_bases", summary="获取知识库")
@handle_exception("获取知识库失败")
def get_knowledge_bases(request):
    records = KnowledgeBase.objects.all()
    return R.ok(KnowledgeBasSerializer(records, many=True).data)


@manager_customer_service_router.post("/knowledge_base", summary="添加知识库")
@handle_exception("添加知识库失败")
def add_knowledge_base(request, data: AddKnowledgeBaseSchema):
    KnowledgeBase.objects.create(file=data.file)
    return R.ok(msg="添加成功")


@manager_customer_service_router.delete("/knowledge_base/{knowledge_base_id}", summary="删除知识库")
@handle_exception("删除知识库失败")
def delete_knowledge_base(request, knowledge_base_id: int):
    if not KnowledgeBase.objects.filter(id=knowledge_base_id).exists():
        return R.error("该知识库不存在")
    knowledge = KnowledgeBase.objects.filter(id=knowledge_base_id).first()
    if not os.path.exists(knowledge.file):
        return R.error("该知识库文件不存在")
    os.remove(knowledge.file)
    knowledge.delete()
    return R.ok(msg="删除成功")


@manager_customer_service_router.get("/service_switch", summary="获取客服开关状态")
@handle_exception("获取客服开关状态失败")
def get_service_switch(request):
    if not os.path.exists("conf/service_switch.txt"):
        return R.fail("获取客服开关状态失败")
    with open("conf/service_switch.txt", "r") as f:
        return R.ok(f.read())


@manager_customer_service_router.post("/service_switch", summary="设置客服开关状态")
@handle_exception("设置客服开关状态失败")
def set_service_switch(request, data: ChangeServiceStatusSchema):
    if data.status not in ["on", "off"]:
        return R.fail("设置客服开关状态失败")
    with open("conf/service_switch.txt", "w") as f:
        f.write(data.status)
    return R.ok(msg="设置成功")


@manager_customer_service_router.get("/services", summary="获取客服列表", response=List[CustomerManageResponseSchema])
@handle_exception("获取客服列表失败")
@paginate(MyPagination)
def get_services(request):
    services = CustomerManage.objects.all()
    return services


@manager_customer_service_router.post("/service", summary="添加客服")
@handle_exception("添加客服失败")
def add_service(request, data: AddServiceSchema):
    customer = CustomerManage.objects.create(**data.dict())
    customer.user = request.user
    customer.save()
    return R.ok(msg="添加成功")


@manager_customer_service_router.delete("/service/{service_id}", summary="删除客服")
@handle_exception("删除客服失败")
def delete_service(request, service_id: int):
    if not CustomerManage.objects.filter(id=service_id).exists():
        return R.error("该客服不存在")
    customer = CustomerManage.objects.filter(id=service_id).first()
    customer.delete()
    return R.ok(msg="删除成功")
